import { _decorator, Component, Node, Sprite } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FrameAnimaton')
/**
 * 帧动画工具
 */
export class FrameAnimaton extends Component {

    //精灵图
    private BgSprite: Sprite = null;

    //纹理名称
    private SpriteFrameName: string = "";

    //帧动画数量
    private FrameCount: number = 0;

    //记录当前帧
    private FrameIndex: number = 0;

    //帧率
    private FrameRate: number = 0;

    //记录帧
    private RemFrame: number = 0;

    //回调函数
    private Cb: Function = null;

    //播放次数
    private PlayCount: number = 0;

    /**
     * 更新帧动画信息
     */
    public UpdateFrameAnimation(_bgsprite: Sprite, _spriteframename: string, _framecount: number, _playcount: number, _cb: Function = null, _framerate: number = 24) {
        this.BgSprite = _bgsprite;
        this.SpriteFrameName = _spriteframename;
        this.FrameCount = _framecount;
        this.FrameIndex = 1;
        this.RemFrame = 0;
        this.FrameRate = 60 / _framerate;
        this.BgSprite.spriteFrame = app.resManager.SpriteFrames[this.SpriteFrameName + this.FrameIndex];
        this.PlayCount = _playcount;
        this.Cb = _cb;
    }

    protected update(dt: number): void {
        if (this.BgSprite && this.PlayCount != 0) {
            this.RemFrame++;
            if (this.RemFrame >= this.FrameRate) {
                this.RemFrame = 0;
                this.FrameIndex++;
                if (this.FrameIndex > this.FrameCount) {
                    this.FrameIndex = 1;
                    this.PlayCount--;

                    if (this.PlayCount == 0) {
                        this.Cb && this.Cb();
                    }
                }

                this.BgSprite.spriteFrame = app.resManager.SpriteFrames[this.SpriteFrameName + this.FrameIndex];
            }
        }
    }

}

